# encoding: utf-8
""" 
@version: v1.0 
@author: autumner 
@license: Apache Licence  
@contact: 18322313385@163.com 
@site:  
@software: PyCharm 
@file: class_structure3.py 
@time: 2019/6/20 15:00
"""

'''
1.简化数据结构的初始化，省去烦人的__init__()初始化函数
2.增加关键字参数设置
3.向不在_fields中的名称加入到属性中；
4.使用self.__dict__.update方法可以替代setattr方法，但当一个子类定义了__slots__或者通过property(或描述器)来包装某个属性时那么还是使用setattr方法比较恰当；
'''

class Structure3:
    # Class variable that specifies expected fields
    _fields = []

    def __init__(self, *args, **kwargs):
        if len(args) != len(self._fields):
            raise TypeError('Expected {} arguments'.format(len(self._fields)))

        # Set the arguments
        for name, value in zip(self._fields, args):
            setattr(self, name, value)

        # Set the additional arguments (if  any)
        extra_args = kwargs.keys() - self._fields
        for name in extra_args:
            setattr(self, name, kwargs.pop(name))

        if kwargs:
            raise TypeError('Duplicate values numbers "{}" that for "{}"'.format(len(kwargs),','.join(kwargs)))

# Example use
if __name__ == '__main__':
    class Stock(Structure3):
        _fields = ['name', 'shares', 'price']


    s1 = Stock('ACME', 50, 91.1)
    print(vars(s1))

    s2 = Stock('ACME', 50, 91.1, name='Tom', date='20/06/2019', price=32.1)
    print(s2.__dict__)



    # print(help(Stock))
